import { ref,reactive } from 'vue'
import { updatepassword } from '~/api/admin/manager.js'
import { useRouter } from 'vue-router'
import { showModal,toast } from '~/composables/util.js'
import { useStore } from 'vuex'

export function useRepassword (){
  const router = useRouter()
  const store = useStore()
  //修改密码
  const formDrawerRef = ref(null)
  const form = reactive({
    new_password: '',
    new_password_confirm: '',
  })

  const rules = {
    new_password : [  //验证规则
      { required: true, message: '新密码不能为空', trigger: 'blur' },
      //{ min: 3, max: 5, message: '用户名在3-5个字符内', trigger: 'blur' },
    ],
    new_password_confirm : [
      { required: true, message: '确认密码不能为空', trigger: 'blur' },
      //{ min: 3, max: 12, message: '密码在3-12个字符内', trigger: 'blur' },
    ],
  }
  const formRef = ref(null) 
  const onSubmit = ()=>{
    formRef.value.validate((valid)=>{
      //console.log(valid)
      if(!valid){
        return false
      }
      formDrawerRef.value.showLoading()
      updatepassword(form)
      .then(res=>{
        toast('修改密码成功，请重新登录')
        store.dispatch('logout')
        router.push('/admin/login')
      }).finally(()=>{
        formDrawerRef.value.hideLoading()
      })
    })
  }
  const openRePasswordForm =()=> formDrawerRef.value.open()

  return {
    formDrawerRef,form,rules,formRef,onSubmit,openRePasswordForm
  }
}

export function useLogout(){
  const router = useRouter()
  const store = useStore()
  function handlogout(){
    showModal('是否退出登录？')
    .then(res=>{
      store.dispatch('logout')
      router.push('/admin/login')
      toast('退出登录成功')
    })
  }

  return {
    handlogout
  }
}